package com.study.mythread.juc.ticket;

import java.util.concurrent.TimeUnit;

/**
 * @program: java-study-of-learner
 * @description: 使用Runnable接口加入同步
 * @author: future
 * @create: 2021-01-16 20:24
 **/
public class SaleTicketV3 implements Runnable {
    private int num = 50;

    public static void main(String[] args) {
        SaleTicketV3 v3 = new SaleTicketV3();
        Thread t1 = new Thread(v3);
        t1.start();
        Thread t2 = new Thread(v3);
        t2.start();
        Thread t3 = new Thread(v3);
        t3.start();
    }

    public synchronized void sale() {
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + " 我们开始卖票吧3 ：" + num--);
        }
    }

    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                sale();
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
